<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/7
 * Time: 15:39
 */

namespace app\api\controller;

use app\api\service\MainService;
use controller\BasicApi;
use service\AccountService;
use service\SendMsgService;
use service\WechatService;
use think\Db;

class user extends BasicApi
{

    public function getsession(){
        $res =session('validate_code');
        print_r($res);
    }
    public function setsession(){
        $sms_time_out =  1800;
        $code = mt_rand(1000, 9999);
        cookie("code",$code);
        $info['code'] = $code;
        $info['is_check'] = 0;
        $info['time'] = time() + $sms_time_out; //有效验证时间
        $info['sender'] = 18273392280;
        session('validate_code', $info);
    }
    public function getopenid()
    {
        $code = $this->request->param("code");
        $arr = WechatService::getOpenId($code);
        $this->success('',$arr);
    }

    /**
 * 登陆
 * http://fri.game.com/index/User/login?mobile=xxx&pass=xxx
 */
    public function login() {
        $mobile = $this->request->param('mobile');
        if (!$mobile) {
            $this->error("手机号码不能为空");
        }
        $pass = $this->request->param('pass');
        if (!$pass) {
            $this->error("密码不能为空");
        }
        $userInfo = $user = AccountService::dologin($mobile);
        if($userInfo){
            $passArr = encrypt($pass, $user['salt']);
            //$userInfo['ordernum'] = OrderService::orderAllNum($user['id']);
            if($user && $passArr['pass'] == $user['password']) {
                $this->success('登陆成功',$userInfo);
            } else {
                $this->error("手机号或密码不正确");
            }
        }else{
            $this->error("手机号不正确");
        }

    }

    public function resetPassword(){

        $mobile = $this->request->param('mobile');
        if (!$mobile) {
            $this->error( "手机号码不能为空");
        }
        $oldpass = $this->request->param('oldpass');
        if (!$oldpass) {
            $this->error( "旧密码不能为空");
        }
        $newpass = $this->request->param('newpass');
        if (!$newpass) {
            $this->error( "新密码不能为空");
        }
        $user = AccountService::dologin($mobile);

        $passArr = encrypt($oldpass, $user['salt']);
        if($user && $passArr['pass'] == $user['password']) {

            $newpassArr = encrypt($newpass, $user['salt']);
            $userdata['password'] = $newpassArr['pass'];
            $update = AccountService::save($userdata,$user['id']);
            if($update){
                $this->success( '修改密码成功',$user);
            }else{
                $this->error('修改密码失败');
            }
        }else{
            $this->error("手机号码或者旧密码错误");
        }
    }

    public function orderAllNum() {
        $uid = $this->request->param('uid');
        $params['account_id'] = $uid;
        $userInfo['ordernum'] = OrderService::orderAllNum($uid);
        $this->responseSuccess($userInfo, '登陆成功');
    }

    /*
     * 注册
     * http://fri.game.com/index/User/login?mobile=xxx
     */
    public function reg() {
        $mobile = $this->request->param('mobile');
        $nick_name = $this->request->param('nick_name');
        $avatarUrl = $this->request->param('avatarUrl');
        $openid = $this->request->param('openid');
        if (!$mobile) {
            $this->error("手机号码不能为空");
        }
        $c = AccountService::doreg($mobile);
        if($c) {
            $userInfo = AccountService::dologin($mobile);
            $this->success('登录成功',$userInfo);
        }else{
            $uid = AccountService::createUser($nick_name,$mobile,$avatarUrl,$openid);
            if($uid){
                $userInfo = AccountService::find($uid);
                $this->success( '注册成功,默认密码111111',$userInfo);
            }else{
                $this->error('该微信号已绑定账号');
            }

        }
    }

    /**
     * 修改信息
     *
     */
    public function changeInfo() {
        $data['mobile'] = $mobile = $this->request->param('mobile');
        $data['id'] = $id = $this->request->param('id');
        $data['nick_name'] = $nick_name = $this->request->param('nick_name');
        $data['avatarUrl'] = $cover = $this->request->param('cover');
        $password =  $this->request->param('password','');
        $data['age'] =  $this->request->param('age','');
        $data['identity_card'] =  $this->request->param('identity_card','');
        $data['gender'] =  $this->request->param('gender','');
        if(!empty($password)){
            $data['password'] = $password ;
        }
        $userInfo = AccountService::checkPhone($data);
        if($userInfo){
            $this->success('修改成功',$userInfo);
        }else{
            $this->error("修改失败,该手机号码已绑定其他账号");
        }
    }

    public function sendmessage() {
        $phone = $this->request->param('send');
        if (!$phone) {
            $this->error('参数错误');
        }

        if (!$this->checkMobile($phone)) {
            $this->error("手机号码错误", 401);
        }

        $send = session('validate_code');
        if (!empty($send) && $send['time'] > time() && $send['sender'] == $phone) {
            //在有效期范围内 相同号码不再发送
            return json(array('status' => -1, 'msg' => '规定时间内,不要重复发送验证码','res'=>$send));
        }

        $resa = self::sendSms($phone);
        $res = array('status' => 1, 'msg' => '发送成功','res'=>$resa);
        return json($res);
    }

    /**
     * 发送短信
     */
    public function sendSms($phone) {
        $sms_time_out =  1800;
        $code = mt_rand(1000, 9999);
        cookie("code",$code);
        $params = array ();

        $info['code'] = $code;
        $info['is_check'] = 0;
        $info['time'] = time() + $sms_time_out; //有效验证时间
        $info['sender'] = $phone;
        session('validate_code', $info);
        $AccountInfo = SendMsgService::account();
        $params['action'] = 'send';
        $params['userid'] = $AccountInfo['user_id'];
        $params['account'] = $AccountInfo['user'];
        $params['password'] = $AccountInfo['pwd'];
        $params['mobile'] = $phone;
        $params['content'] = '欢迎来到湘上健康,您的注册验证码为'.$code.',有效时间为30分钟 【湘上健康】';
        $params['sendTime'] = '';
        $params['extno'] = '';

        $res =  self::send_post($AccountInfo['url'],$params);
        return $info;
    }

    function send_post($url, $post_data) {
        $postdata = http_build_query($post_data);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' => 'Content-type:application/x-www-form-urlencoded',
                'content' => $postdata,
                'timeout' => 15 * 60 // 超时时间（单位:s）
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        return $result;
    }
    /**
     * 手机号码是否正确
     */
    private function checkMobile($mobile) {
        return preg_match('/^0?(13|15|17|18|14)[0-9]{9}$/i', $mobile);
    }
    public function orderuser(){
    $account_id = $this->request->param('uid');
    $memberList = MainService::getMemberList($account_id);
    $this->success( '获取成功',$memberList);
}
    public function orderuserinfo(){
        $id = $this->request->param('id',0);
        $memberList = MainService::findMember($id);
        $this->success( '获取成功',$memberList);
    }
    public function saveorderuserinfo(){
        $id = $this->request->param('id',0);
        if($id){
            $data['id'] = $id;
        }
        $data['account_id'] =  $account_id = $this->request->param('account_id');
        $data['name'] =  $name = $this->request->param('name');
        $data['mobile'] =  $mobile = $this->request->param('mobile');
        $data['age'] =  $age = $this->request->param('age');
        $data['sex'] =  $sex = $this->request->param('sex');
        $data['card_no'] =  $sex = $this->request->param('card_no');
        $status = MainService::saveMemberInfo($data);
        if($status){
            $this->success( '保存体检人信息成功');
        }else{
            $this->error('保存体检人信息失败');
        }
    }
    public function exam_messagelist(){
        $account_id = $this->request->param('account_id',0);
        $page = $this->request->param('page',1);
        $pagesize = 6;
        $res =  Db::name('exam_mesage')
            ->where('account_id',$account_id)
            ->whereOr('account_id','0')
            ->order('create_time desc')
            ->limit(($page-1)*$pagesize,$pagesize)
            ->select();
       foreach ($res as $key=>&$item){
           $item['create_time'] = date('Y-m-d H:i:s',$item['create_time']);
       }
        $this->success( '获取信息成功',$res);
    }
    public function oldmessage(){
        $msgid= $this->request->param('msg_id',0);
        $data['isnew'] = 0;
        Db::name('exam_mesage')->where('id',$msgid)->update($data);
        $res =  Db::name('exam_mesage')->find($msgid);
        $res['create_time'] = date('Y-m-d H:i:s',$res['create_time']);
        $this->success( '修改成功',$res);

    }


    public function isgroup(){
        $id = $this->request->param('id');
        $res = AccountService::find($id);
        if($res['group']['gid']){
            $this->success('获取成功',$res);
        }else{
            $this->error('不是团检人员');
        }
    }
    public function groupinfo(){
        $groupid = $this->request->param('id');
        $res = Db::name('exam_group_member')->find($groupid);
        if($res){
            $res['groupinfo']   = $groupinfo =  Db::name('exam_group')->find($res['group_id']);
            $res['enterprise']  = Db::name('exam_enterprise')->where('id',$groupinfo['enterprise_id'])->find();
            $res['setinfo']     = Db::name('exam_set')->where('id',$groupinfo['group_set_id'])->find();
            $res['mecinfo']     = Db::name('exam_mec')->where('id',$groupinfo['mec_id'])->find();
            $res['orderinfo']    = MainService::getOrderInfoByOrdersn($res['order_sn']);
            $this->success('获取成功',$res);
        }else{
            $this->error('不是团检人员');
        }
    }
    public function doopenidlogin(){
        $openid = $this->request->param('openid');
        $res = Db::name('account')->where('openid',$openid)->find();
        if($res){
            $this->success('登录成功',$res);
        }else{
            $this->error('微信登录失败，请先注册');
        }
    }
    public function getwxphone(){
        $iv = $this->request->param("iv");
        $code = $this->request->param("code");
        $openid = $this->request->param('openid');
        $encryptedData = $this->request->param("encryptedData");
        $arr = WechatService::getOpenId($code);
        if (strlen($arr['session_key']) != 24) {
            return 1;
        }
        $aesKey=base64_decode($arr['session_key']);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($encryptedData);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );
        if( $dataObj  == NULL )
        {
            return -41003;
        }
        $data = json_decode($result,true);
        $mobile = $userdata['tel'] = $data['phoneNumber'];
        $nick_name = $this->request->param('nick_name');
        $avatarUrl = $this->request->param('avatarUrl');

        $c = AccountService::doreg($userdata['tel']);
        if($c) {
            $userInfo = AccountService::dologin($mobile);
            $this->success('绑定成功',$userInfo);
        }else{
            $uid = AccountService::createUser($nick_name,$mobile,$avatarUrl,$openid);
            if($uid){
                $userInfo = AccountService::find($uid);
                $this->success( '注册成功,默认密码111111',$userInfo);
            }else{
                $this->error('该微信号已绑定账号');
            }
        }
    }
}
